import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Modal, Icon, Radio, message, Spin } from 'antd';
import { toJS } from 'mobx';
import { WeaTableNew, WeaSwitch } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { WeaRightMenu, WeaTop, WeaTab, WeaErrorPage, WeaTools, WeaInput, WeaAlertPage, WeaReqTop, WeaNewScroll, WeaSearchGroup, WeaFormItem, WeaTextarea, WeaUpload, WeaError, WeaHelpfulTip } from 'ecCom';
import WeaRightLeftLayout from '../comp/weaCrmRightLeft';

const getKey = WeaTools.getKey;
import WeaCrmContacterTableEdit from '../comp/WeaCrmTableEdit/contacterEditTable.js';
import CustomerContact from '../public/CustomerContact';
import { WeaLocaleProvider } from 'ecCom';
import { isEmail, isURL } from '../../util/index';

const getLabel = WeaLocaleProvider.getLabel;

let that = '';
@observer
export default class ViewCustomerBase extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      canAdd: true,
      showRightLog: true,
    };
    that = this;
  }
  componentDidMount() {
    const { contentStore } = this.props;
    contentStore.initCrmInfo({ customerId: contentStore.customerId });
  }

    createHeight = () => {
      const contentH = jQuery('.wea-new-top-req-content').height() - 204;
      return contentH;
    }
    setCountryRef = (ref) => {
      ViewCustomerBase.counRef = ref;
    }

    setProvRef = (ref) => {
      ViewCustomerBase.provRef = ref;
      const alertModel = ref.alertModel.bind(ref);
      ViewCustomerBase.provRef.alertModel = () => {
        const store = this.props.contentStore;
        const { country } = store.form.getFormParams();
        // 绕过原来的加载城市的逻辑
        ref.props.replaceDatas = [1];
        alertModel();
        ref.props.replaceDatas = [];

        this.fetchProvs('provRef', country ? 'prov' : 'coun');
      };
    }

    setCityRef = (ref) => {
      const alertModel = ref.alertModel.bind(ref);

      ViewCustomerBase.cityRef = ref;
      ViewCustomerBase.cityRef.alertModel = () => {
        const store = this.props.contentStore;
        const { province } = store.form.getFormParams();
        // 绕过原来的加载城市的逻辑
        ref.props.replaceDatas = [1];
        alertModel();
        ref.props.replaceDatas = [];

        const callback = () => {
          if (province) {
            const { provs } = ViewCustomerBase.cityRef.state;
            let proObj = provs.find(({ id }) => id === province);
            if (typeof (proObj) === 'undefined') {
              proObj = {
                id: province,
                type: 'prov',
              };
            }
            ViewCustomerBase.cityRef.tabsChange('city');
            proObj && ViewCustomerBase.cityRef.provClick(null, { ...proObj, isParent: true });
          } else {
            const { provs } = ViewCustomerBase.cityRef.state;
            const provObj = provs.find(({ id }) => id === province);
            provObj && ViewCustomerBase.cityRef.provClick(null, provObj);
          }
        };

        this.fetchProvs('cityRef', province ? 'city' : 'prov', callback);
      };
    }

    setDistrictRef = (ref) => {
      const alertModel = ref.alertModel.bind(ref);
      const store = this.props.contentStore;
      const { province, city, district } = store.form.getFormParams();
      ViewCustomerBase.disRef = ref;
      ViewCustomerBase.disRef.alertModel = () => {
        // 绕过原来的加载城市的逻辑
        ref.props.replaceDatas = [1];
        alertModel();
        ref.props.replaceDatas = [];
        const callback = () => {
          if (city) {
            const { citys } = ViewCustomerBase.disRef.state;
            let cityObj = citys.find(({ id }) => id === city);
            if (typeof (cityObj) === 'undefined' && city != '0') {
              cityObj = {
                id: city,
                type: 'city',
              };
            }
            ViewCustomerBase.disRef.tabsChange('district');
            cityObj && ViewCustomerBase.disRef.cityClick(null, { ...cityObj, isParent: true });
          } else {
            const { provs } = ViewCustomerBase.disRef.state;
            const provObj = provs.find(({ id }) => id === province);
            provObj && ViewCustomerBase.disRef.provClick(null, provObj);
          }
        };
        this.fetchProvs('disRef', province ? 'city' : 'prov', callback);
      };
    }

    fetchProvs = (refName, activeKey, callback = () => {}) => {
      const { country } = this.props.contentStore.form.getFormParams();
      const obj = {
        type: 'coun',
        id: country || 1,
        isParent: true,
      };
      let url = ViewCustomerBase[refName].state.url;
      url = `${url}${WeaTools.getFd({ ...obj })}&`;
      WeaTools.callApi(url, 'GET').then((datas) => {
        ViewCustomerBase[refName].setState({
          counSelected: obj.id,
          provs: datas.datas,
          activeKey,
        });
        callback();
      });
    }

    resetCityBrowser() {
      ViewCustomerBase.cityRef.setState({
        activeKey: 'prov',
        citySelected: '',
        provsSelected: '',
        citys: [],
      });
    }

    resetDistrictBrowser() {
      ViewCustomerBase.disRef.setState({
        activeKey: 'city',
        citySelected: '',
        districtSelected: '',
        citys: [],
        districts: [],
      });
    }

    updateCountry(targetRef) {
      const country = targetRef.state.countrys.find(({ id }) => id === targetRef.state.counSelected);
      const { counRef } = ViewCustomerBase;
      if (country && typeof (country) !== 'undefined' && (typeof (counRef) !== 'undefined')) {
        const { form } = this.props.contentStore;
        const countryField = {
          country: {
            value: country.id,
            valueObj: [{ id: country.id, name: country.name }],
          },
        };

        form.updateFields(countryField);
        ViewCustomerBase.counRef.countryClick(null, country);
        ViewCustomerBase.counRef.tabsChange('coun');
      }
    }
    onChangeHandle=(res, obj) => {
      const store = this.props.contentStore;
      const { form } = store;
      const { counRef, provRef, cityRef, disRef } = ViewCustomerBase;

      const provRefIsNotUndefined = typeof (provRef) !== 'undefined';
      const cityRefIsNotUndefined = typeof (cityRef) !== 'undefined';
      const disRefIsNotUndefined = typeof (disRef) !== 'undefined';

      if (res.country) {
        const { value } = res.country;
        const empty = {
          province: { value: '', valueObj: [{}] },
          city: { value: '', valueObj: [{}] },
          district: { value: '', valueObj: [{}] },
        };
        counRef.state.countrys.forEach((p) => {
          p.selected = p.id === value;
        });
        if (value) {
          if (provRefIsNotUndefined && provRef.state.counSelected !== value && provRef.state.counSelected != '') {
            form.updateFields(empty);
          }
          if (cityRefIsNotUndefined && cityRef.state.counSelected !== value && cityRef.state.counSelected != '') {
            form.updateFields(empty);
          }
          if (disRefIsNotUndefined && disRef.state.counSelected !== value && disRef.state.counSelected != '') {
            form.updateFields(empty);
          }
        } else {
          form.updateFields(empty);
        }

        form.updateFields(res);
      }

      if (res.province) {
        const { value } = res.province;
        const empty = {
          city: { value: '', valueObj: [{}] },
          district: { value: '', valueObj: [{}] },
        };

        provRef.state.provs.forEach((p) => {
          p.selected = p.id === value;
        });

        if (value) {
          // const isDiff = provRef.state.provsSelected !== value
          // &&cityRefIsNotUndefined&& cityRef.state.provsSelected !== value
          // &&disRefIsNotUndefined&& disRef.state.provsSelected !== value;
          const provObj = { ...obj.valueObj[0], isParent: true };

          this.updateCountry(provRef);
          cityRefIsNotUndefined && cityRef.provClick(null, provObj);

          if (cityRefIsNotUndefined && cityRef.state.provsSelected !== value) {
            form.updateFields(empty);
          }
          if (disRefIsNotUndefined && disRef.state.provsSelected !== value) {
            form.updateFields(empty);
            disRef.provClick(null, provObj);
          }
        } else {
          form.updateFields(empty);
          this.resetCityBrowser();
          this.resetDistrictBrowser();
          cityRefIsNotUndefined && cityRef.tabsChange('prov');
          disRefIsNotUndefined && disRef.setState({
            provsSelected: '',
            activeKey: 'prov',
          });
          provRef.state.provs.forEach((p) => {
            p.selected = false;
          });
          provRef.setState({
            provsSelected: '',
          });
        }
        form.updateFields(res);
      }

      if (res.city) {
        const { value } = res.city;
        const empty = {
          district: { value: '', valueObj: [{}] },
        };

        cityRef.state.citys.forEach((c) => {
          c.selected = c.id === value;
        });
        if (value) {
          const { countrys, provs, counSelected, provsSelected } = cityRef.state;
          const prov = provs.find(({ id }) => id === provsSelected);
          const country = countrys.find(({ id }) => id === counSelected);
          const isDiff = cityRef.state.citySelected !== value
                || (disRefIsNotUndefined && disRef.state.citySelected !== value);

          this.updateCountry(cityRef);

          if (prov) {
            provRefIsNotUndefined && provRef.provClick(null, prov);
            provRefIsNotUndefined && provRef.tabsChange('prov');
            disRefIsNotUndefined && disRef.countryClick(null, { ...country, isParent: true });
            disRefIsNotUndefined && disRef.provClick(null, { ...prov, isParent: true });
          }
          disRefIsNotUndefined && disRef.cityClick(null, { ...obj.valueObj[0], isParent: true });
          if (disRefIsNotUndefined && disRef.state.citySelected !== value) {
            form.updateFields(empty);
          }
        } else {
          cityRef.state.citys.forEach((c) => {
            c.selected = false;
          });
          cityRef.setState({
            citySelected: '',
          });
          this.resetDistrictBrowser();
          form.updateFields(empty);
        }
        form.updateFields(res);
      }

      if (res.district) {
        const { value } = res.district;
        let activeKey;
        if (provRefIsNotUndefined) {
          activeKey = ViewCustomerBase.provRef.state;
        }
        disRef.state.districts.forEach((d) => {
          d.selected = d.id === value;
        });
        if (provRefIsNotUndefined) {
          if (provRef.state.provsSelected !== disRef.state.provsSelected) {
            provRef.state.provs.forEach((p) => {
              p.selected = p.id === disRef.state.provsSelected;
            });
            provRef.setState({
              provsSelected: disRef.state.provsSelected,
            });
          }
        }

        if (cityRefIsNotUndefined) {
          if (cityRef.state.citySelected !== disRef.state.citySelected) {
            cityRef.state.citys.forEach((c) => {
              c.selected = c.id === disRef.state.citySelected;
            });
            cityRef.setState({
              citySelected: disRef.state.citySelected,
            });
          }
        }

        if (value) {
          if (!activeKey) {
            provRefIsNotUndefined && provRef.tabsChange('prov');
          }
          store.setAddressInfo(value);
        } else {
          disRef.setState({
            districtSelected: '',
          });
        }
      }
    }

    render() {
      const { contentStore, location } = this.props;
      const { canAdd, showRightLog } = this.state;
      const { form, rightLevel, contacterData, conditioninfo, contacterInfo, customerId, crmInfoContactStore, user, loadingInfo, currentPageState, canView, onlyView } = contentStore;
      const urlParams = location.query;
      const contacterObj = toJS(contacterInfo);
      let columns = [];
      let columnsData = [];
      if (contacterObj.enableContacter) {
        columns = contacterObj.columns;
        if (!urlParams.fromPortal) {
          const operationCol = {
            title: getLabel(104, '操作'),
            com: [{ formItemType: 'OPERATION', domkey: ['OPERATION'] }],
            className: 'table-edit-opertion',
          };
          columns.push(operationCol);
        }
        columnsData = contacterObj.columnsData;
      }
      let fromPortal = false;
      if (user.logintype == 2) {
        fromPortal = true;
      }
      let content = [];
      if (loadingInfo) {
        const loadingCom = <div style={{ backgroundColor: 'transparent', position: 'absolute', width: '100%', top: '48%', textAlign: 'center' }}><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@tlk3fp`} spinning /></div>;
        content = [loadingCom];
      } else {
        content.push(
          <div>
            {this.getInfoForms(conditioninfo)}
            {
              contacterObj.enableContacter &&
              <WeaCrmContacterTableEdit
                ecId={`${this && this.props && this.props.ecId || ''}_WeaCrmContacterTableEdit@cwj69t@ccte`}
                ref="crmCont"
                title={contacterObj.title}
                showGroup
                needAdd={!(rightLevel == 1 || currentPageState == 'readOnly')}
                needCopy={false}
                columns={columns}
                datas={columnsData}
                canAdd={canAdd}
                onChange={this.onChange.bind(this)}
                onAddChange={this.onAddChange.bind(this)}
                onEditChange={this.onContacterEditChange.bind(this)}
                showRightContactlog={this.showRightContactlog.bind(this)}
                parentStore={contentStore}
                onSave={this.doSaveContracter.bind(this)}
                onDelete={this.doDelete.bind(this)}
                needAddContact={false}
              />
            }
          </div>,
        );
      }
      return (
        <div >
          {
            fromPortal &&
            <WeaNewScroll
              ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@9gxv3s`}
              height={'100%'}
              children={
                content
              }
            />
          }
          {
            !fromPortal && (!canView && onlyView) ? <WeaNewScroll
              ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@drnnf7`}
              height={'100%'}
              children={
                content
              }
            /> : <WeaRightLeftLayout
              ecId={`${this && this.props && this.props.ecId || ''}_WeaRightLeftLayout@km7nh5`}
              ref="RLlayout"
              defaultShowLeft={showRightLog}
              type={30}
              leftCom={<WeaNewScroll
                ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@fct608`}
                height={'100%'}
                children={
                  content
                }
              />
              }
            >
              <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@n02h5h`} datas={[]} >
                <div className="customer-contact-title">{getLabel(6082, '客户联系')}</div>
                <div className="customer-contact-bottomline" />
                <CustomerContact ecId={`${this && this.props && this.props.ecId || ''}_CustomerContact@99onqh`} ref="customerContact" contentStore={crmInfoContactStore} params={{ from: 'base', customerId }} type="card" location={location} />
              </WeaRightMenu>
            </WeaRightLeftLayout>
          }

        </div>);
    }

    getInfoForms(conditioninfo) {
      const { contentStore } = this.props;
      const { form } = contentStore;
      const { isFormInit } = form;
      const group = [];
      isFormInit && toJS(conditioninfo).map((c,indexGroup) => {
        // console.log(JSON.stringify(toJS(conditioninfo)))
        const items = [];
        c.items.map((fields, index) => {
          const oldValue = fields.value;
          let isunderline = '';
          if (fields.viewAttr == '1' || (fields.conditionType == 'BROWSER' && fields.browserConditionParam.viewAttr == '1')) { fields.hasBorder = false; isunderline = 'underline'; } // 只读样式控制
          let dom;
          // if(fields.domkey[0] == "email"){   //邮件校验
          //     // const req =  new RegExp("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$");
          //     const key = getKey(fields);
          //     const bindObj = form.$(key);
          //     dom = <div><WeaInput
          //         {...bindObj.bind() }
          //         // onBlur={(v) => {
          //         //     if(v != ""){
          //         //         if(isEmail(v)){
          //         //             this.onEditChange2(oldValue, fields, v);
          //         //         }else{
          //         //             // 不符合校验规则，将数据重置回去
          //         //             message.error(getLabel(71,"邮件")+getLabel(15196,"格式")+getLabel(127353,"错误"));
          //         //             contentStore.resetEmail(fields.domkey[0],oldValue);
          //         //         }
          //         //     }else{
          //         //         this.onEditChange2(oldValue, fields, v)
          //         //     }

          //         // }}
          //         {...fields}
          //         value={bindObj.values()}
          //     />
          //     </div>
          // }else
          if (fields.conditionType == 'INPUT' || fields.conditionType == 'TEXTAREA') {
            dom = <div style={{ color: 'bule' }}> <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@5pp1l8@${index}`} fieldConfig={fields} form={form} onBlur={(v) => { this.onEditChange2(oldValue, fields, v); }} /></div>;
          } else {
            const isBrowser = fields.formItemType === 'BROWSER';
            const browserType = fields.browserConditionParam ? fields.browserConditionParam.type : '';
            const isCountryBrowser = isBrowser && browserType === '258';
            const isProvBrowser = isBrowser && browserType === '2222';
            const isCityBrowser = isBrowser && browserType === '58';
            const isDisBrowser = isBrowser && browserType === '263';

            if (isCountryBrowser) {
              fields.initFunc = this.setCountryRef;
            } else if (isProvBrowser) {
              fields.initFunc = this.setProvRef;
            } else if (isCityBrowser) {
              fields.initFunc = this.setCityRef;
            } else if (isDisBrowser) {
              fields.initFunc = this.setDistrictRef;
            }


            dom = (<WeaSwitch
              ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@6tf584@${index}`}
              fieldConfig={fields}
              form={form}
              onChange={(a, b) => {
                const ids = b.value;
                if (fields.conditionType == 'UPLOAD') {
                  form.updateFields({ [fields.domkey[0]]: { value: `${ids}` } }, false);
                  this.onEditChange2(oldValue, fields, `${ids}`);
                } else {
                  this.onChangeHandle(a, b);
                  this.onEditChange(oldValue, fields, ids);
                }
              }}
            />);
          }
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@aumxh2@${index}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
              error={form.getError(fields)}
              underline={isunderline}
            >
              <div style={{ display: 'table-cell', verticalAlign: 'bottom' }}>
                <WeaError
                  ecId={`${this && this.props && this.props.ecId || ''}_WeaError@9qwc0g@${index}`}
                  tipPosition="bottom"
                  style={{ width: '100%', display: 'block' }}
                  ref={fields.domkey[0]}
                  error={`${'"' + `${fields.label}` + '"'}${getLabel(21423, '未填写')}`}
                >
                  {dom}
                </WeaError>
              </div>
            </WeaFormItem>),
            colSpan: 1,
          });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@1bwruk@${indexGroup}`} needTigger title={c.title} showGroup={c.defaultshow} items={items} />);
      });
      return group;
    }
    onEditChange(oldvalue = '', field, value) {
      let oldValueSpan = oldvalue;
      if (field.formItemType == 'BROWSER') {
        oldValueSpan = field.showName;
      }
      const { customerId, customerInfoEdit, conditioninfo, form } = this.props.contentStore;
      const fit = field.conditionType.toUpperCase();
      const fieldName = field.domkey[0];

      if (value !== oldvalue) {
        if (field.viewAttr == 3 && value == '') {
          this.refs[fieldName].showError();
          setTimeout(() => {
            form.initFormFields(conditioninfo);
          }, 100);
          return false;
        }
        const params = {
          customerId,
          fieldName,
          oldValue: oldvalue,
          oldValueSpan,
          newValue: value,
          fieldType: fit,
        };
        customerInfoEdit(params);
      }
    }

    onEditChange2 = (oldvalue = '', field, value) => {
      const { customerId, customerInfoEdit, conditioninfo, form, customerRepeatCheck } = this.props.contentStore;
      const fit = field.conditionType.toUpperCase();
      const fieldName = field.domkey[0];
      // 验证通过, balabala业务代码
      if (value !== oldvalue) {
        if (field.viewAttr == 3 && value == '') {
          this.refs[fieldName].showError();
          setTimeout(() => {
            form.initFormFields(conditioninfo);
          }, 100);
          return false;
        }
        const params = {
          customerId,
          fieldName,
          oldValue: oldvalue,
          newValue: value,
          fieldType: fit,
        };
        if (fieldName == 'name') {
          customerRepeatCheck(params);
        } else {
          customerInfoEdit(params);
        }
      }
    }
    onChange(datas) {
      const { contentStore } = this.props;
      contentStore.updateContacterData(datas);
    }
    onAddChange = () => {
      this.setState({ canAdd: false });
    }
    onContacterEditChange = (field, index, key, value) => {
      const { customerId, contacterData, editContracterData } = this.props.contentStore;
      const oldValue = contacterData[index][key];
      const params = {
        id: field.contacterid,
        customerId,
      };
      params.index = index;
      params.fieldName = key;
      params.fieldValue = value;
      if (key == 'firstname' && value == '') {
        this.refs.crmCont.showErrors();
        return false;
      }

      // console.log("123456789",field,value,oldValue,key,index)

      if (value !== oldValue) {
        editContracterData(params);
      }
    }

    doSaveContracter = () => {
      const { contacterInfo, customerId, editContracterData } = this.props.contentStore;
      const _datas = toJS(contacterInfo.columnsData);
      const params = _datas[_datas.length - 1];
      params.customerId = customerId;
      // 对新增行的数据做必填检查
      const cde = toJS(contacterInfo.columns);
      let f = true;
      let fieldLabel;
      for (let k = 0; k < cde.length; k++) {
        const formItemType = cde[k].formItemType;
        if (formItemType == 'CHECKBOX' || formItemType == 'RADIO') {
          continue;
        }
        const label = cde[k].title;
        const viewAttr = cde[k].viewAttr;
        const dataIndex = cde[k].dataIndex;
        const value = params[dataIndex];
        if (viewAttr == 3 && (value == '' || typeof (value) === 'undefined')) {
          f = false;
          fieldLabel = label;
          break;
        }
      }
      let finded = false;
      // 检查主联系人
      const cda = toJS(contacterInfo.columnsData);
      for (const d of cda) {
        if (d.main == 1) {
          finded = true;
          break;
        }
      }
      if (!finded) {
        Modal.warning({
          title: getLabel(15172, '系统提示'),
          content: getLabel(18214, '请选择') + getLabel(1262, '主联系人'),
          okText: getLabel(33703, '确定'),
        });
        return;
      }
      if (f) {
        let errorCase = 0;
        const newParams = { contacterid: params.contacterid, columns: cde, columnsData: params };
        cde.map((item, index) => {
          if (item.viewAttr == 3) { // 必填验证，value
            if (('contacteremail' in params) && !isEmail(params.contacteremail)) {
              errorCase = 1;
            }
          } else { // 不是必填
            if (params.contacteremail == '') {
              errorCase = 0;
            } else if (('contacteremail' in params) && !isEmail(params.contacteremail)) {
              errorCase = 1;
            }
          }
        });

        // 可添加别的格式判断
        switch (errorCase) {
          // 邮件格式判断
          case 1:
            message.error(getLabel(71, '邮件') + getLabel(15196, '格式') + getLabel(127353, '错误'));
            break;
            // 其他格式结果
          default:
            editContracterData(newParams);
            this.setState({ canAdd: true });
        }
      } else {
        this.refs.crmCont.showErrors();
      }
    }

    doDelete = () => {
      const { canAdd } = this.state;
      const { contacterInfo, updateContacterData } = this.props.contentStore;
      this.setState({ canAdd: true });
      updateContacterData(toJS(contacterInfo.columnsData).slice(0, -1));
    }

    showRightContactlog(bool, record) {
      this.refs.RLlayout.rightShow();
      this.refs.customerContact.textOnFocus(4);
      this.refs.customerContact.handleChange('contacter', record.contacterid);
    }
}

// jQuery(window).resize(function () {
//     that && that.createHeight && that.createHeight()
// });
